package xyz.qduwo.servlet;


import xyz.qduwo.dao.UserDao;
import xyz.qduwo.entity.UserEntity;
import xyz.qduwo.util.EncryptUtils;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name = "loginServlet", urlPatterns = { "/loginServlet" })
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("name");
        String password = request.getParameter("pwd");
        UserEntity user = UserDao.getByUserName(username);
        System.out.println(user.getUsername());
        if (user.getPassword().equals(EncryptUtils.stringToMD5(password))) {
            HttpSession session = request.getSession(true);
            session.setAttribute("user", username);
            session.setAttribute("userentity",user);
            response.sendRedirect("workbench.jsp");
        } else {
            response.sendRedirect("login.jsp");
        }
    }

}